#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <unistd.h>
#include "mysem.h"

//信号量结构体变量类型
struct mysem_st
{
    int value;
    pthread_mutex_t mutex;
    pthread_cond_t cond;
};

//信号量初始化
mysem_t * mysem_init(int initval)
{
    //申请内存存放信号量结构体
    struct mysem_st * me;
    me = malloc(sizeof(*me));
    if(me == NULL)
        return NULL;
    //给结构体初始化
    me->value = initval;
    pthread_mutex_init(&me->mutex, NULL);
    pthread_cond_init(&me->cond, NULL);
    
    return me;
}
//添加信号量
int mysem_add(mysem_t * ptr, int n)
{
    struct mysem_st * me = ptr;

    pthread_mutex_lock(&me->mutex);
    me->value += n;
    pthread_cond_broadcast(&me->cond);
    pthread_mutex_unlock(&me->mutex);

    return n;
}
//减少信号量
int mysem_sub(mysem_t * ptr, int n)
{
    struct mysem_st * me = ptr;

    pthread_mutex_lock(&me->mutex);
    while(me->value < n)
        pthread_cond_wait(&me->cond, &me->mutex);
    me->value -= n;
    pthread_mutex_unlock(&me->mutex);

    return n;
}
//销毁信号量
int mysem_destroy(mysem_t * ptr)
{
    struct mysem_st * me = ptr;

    pthread_mutex_destroy(&me->mutex);
    pthread_cond_destroy(&me->cond);

    free(me);

    return 0;
}